import { creatCustomer, updateCustomer } from "@/services/customer/custom_api";
import {
  ModalForm,
  ProForm,
  ProFormRadio,
  ProFormText,
  ProFormDateRangePicker,
  ProFormUploadButton
} from "@ant-design/pro-components";
import dayjs from 'dayjs';
import { message ,Tooltip} from "antd";
import { QuestionCircleOutlined } from '@ant-design/icons';
import React, { useState, useEffect } from "react";
import { useIntl } from "umi";
import { CustomerDataVo } from "../../constants"
import type { UploadRequestOption } from 'rc-upload/lib/interface';
import type { UploadFile } from 'antd';
import axios from 'axios';




interface CreateModalProps {
  visible: boolean;
  values?: CustomerDataVo;
  onCancel: () => void;
  onSuccess: () => void;
}
const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 14 },
};
const AddForm: React.FC<CreateModalProps> = ({
  visible,
  values,
  onCancel,
  onSuccess,
}) => {
  const [form] = ProForm.useForm<CustomerDataVo>();
  const intl = useIntl();
  const [validPeriodDateFor, setValidPeriodDateFor] = useState<string>('');
  const [validPeriodDateTo, setValidPeriodDateTo] = useState<string>('');
  // const [updateStatus, setUpdateStatus] = useState<boolean>(false);
  const [editStatus, setEditStatus] = useState<boolean>(false);


  useEffect(() => {
    if (visible) {
      if (values) {
        // console.log("customer:" + JSON.stringify(values));
        setEditStatus(true);
        values.customerType = String(values.customerType);
        values.customerCashType = String(values.customerCashType);
        //todo: logo展示问题
        // values.customerLogo=undefined;
        if (values.validPeriodDateFor) {
          const startTime = dayjs(values.validPeriodDateFor);
          const endTime = dayjs(values.validPeriodDateTo);
          form.setFieldsValue({
            validPeriodDate: [startTime, endTime],
          });
        }
        if (values.customerLogo) {
          console.log("edit logo:" + values.customerLogo);
          initUpload(values.customerLogo, "logo");
        }
      } else {
        const initialStartDate = new Date(); // 当前日期
        const initialEndDate = new Date();
        initialEndDate.setFullYear(initialEndDate.getFullYear() + 5); // 5年天后
        form.setFieldsValue({
          validPeriodDate: [initialStartDate, initialEndDate],
        });
        setValidPeriodDateFor(String(initialStartDate.getTime()))
        setValidPeriodDateTo(String(initialEndDate.getTime()));
        setFileList([]);
      }
      form.setFieldsValue(values || {});
    }
  }, [visible, values]);


  const handleSubmit = async (formValues: CustomerDataVo) => {
    //  console.log("customer1:" + JSON.stringify(values));
    if (formValues.customerLogo) {
      // console.log("customerLogo:" + JSON.stringify(formValues.customerLogo));
      let url;
      formValues.customerLogo.map((item, index) => {
        url = item.url;
      });
      formValues.customerLogo = url;
    }else{
      formValues.customerLogo=undefined;
    }
    if (values?.id) {
      formValues.id = values?.id;
      return await handleUpdateCustomer(formValues);
    }
    try {
      // API调用逻辑
      formValues.validPeriodDateFor = validPeriodDateFor;
      formValues.validPeriodDateTo = validPeriodDateTo;
      const response = await creatCustomer(formValues);

      if (response.code != 0) {
        if (!response.msg) {
          throw new Error(intl.formatMessage({ id: "request.error.operating" }));
        } else {
          // throw new Error(response.msg);
          message.error(response.msg);
          return false;
        }
      }
      message.success(intl.formatMessage({ id: "request.success.operating" }));
      onSuccess();
      resetAllAfterCloseModal();
      return true;
    } catch (error) {
      message.error(intl.formatMessage({ id: "request.error.retry" }));
      return false;
    }
  };

  const handleUpdateCustomer = async (values: CustomerDataVo) => {
    try {
      // API调用逻辑
      values.validPeriodDateFor = validPeriodDateFor;
      values.validPeriodDateTo = validPeriodDateTo;
      const response = await updateCustomer(values);

      if (response.code != 0) {
        if (!response.msg) {
          throw new Error(intl.formatMessage({ id: "request.error.operating" }));
        } else {
          message.error(response.msg);
          return false;
        }
      }
      message.success(intl.formatMessage({ id: "request.success.operating" }));
      onSuccess();
      resetAllAfterCloseModal();
      return true;
    } catch (error) {
      message.error(intl.formatMessage({ id: "request.error.retry" }));
      return false;
    }
  }

  const resetAllAfterCloseModal = () => {
    form.resetFields();
    setFileList([]);
  }

  const handleValuesChange = (changedValues, allValues) => {
    // changedValues 是发生变化的字段
    // allValues 是表单当前所有的值
    // console.log(changedValues);

    if ('validPeriodDate' in changedValues) {
      const [startTime, endTime] = changedValues['validPeriodDate'];
      // console.log('有效期开始时间:', startTime);
      // console.log('有效期结束时间:', endTime);
      setValidPeriodDateFor(startTime)
      setValidPeriodDateTo(endTime)
    }
  };



  const [fileList, setFileList] = useState<UploadFile[]>([]);

  const customUpload = async (options: UploadRequestOption) => {
    const { file, onSuccess, onError, onProgress } = options;

    const formData = new FormData();
    formData.append('file', file as Blob);
    formData.append('bizType', 'cutomerLogo');

    try {
      const response = await axios.post('/admin-api/infra/file/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
        onUploadProgress: ({ total, loaded }) => {
          if (total) {
            const percent = Math.round((loaded / total) * 100);
            onProgress?.({ percent });
          }
        },
      });

      // 示例：假设返回数据结构如下
      // { code: 0, data: 'https://yourcdn.com/path/to/file.png',msg:'' }
      // console.log("upload rep-data:" + JSON.stringify(response));
      if (response.data.code != 0) {
        if (!response.data.msg) {
          throw new Error(intl.formatMessage({ id: "request.error.operating" }));
        } else {
          message.error(response.data.msg);
          return false;
        }
      }

      const uploadedUrl = response.data.data;
      // console.log("uploadedUrl-data:" + uploadedUrl);

      initUpload(uploadedUrl, (file as any).name);
      form.setFieldsValue({ customerLogo: uploadedUrl });

      onSuccess?.(response.data.data, file as any);
    } catch (err) {
      onError?.(err as any);
      message.error(intl.formatMessage({ id: 'request.upload.failed',defaultMessage:" upload failed" }));
    }
  };

  const initUpload = (url: string, name: string) => {
    const uploadedFile: UploadFile = {
      uid: String(Date.now()),
      name: name,
      status: 'done',
      url: url,
    };

    // 更新 fileList 和 form 字段值
    const updatedList = [uploadedFile];
    setFileList(updatedList);
  }

  const cancleModel = () => {
    resetAllAfterCloseModal();
    onCancel();
  }


  return (
    <ModalForm<CustomerDataVo>
      title={values?.id
        ? intl.formatMessage({ id: 'pages.edit' })
        : intl.formatMessage({ id: 'pages.create' })}
      width="40%"
      form={form}
      open={visible}
      onOpenChange={(visible) => !visible && cancleModel()}
      onFinish={handleSubmit}
      onValuesChange={handleValuesChange} // 监听值变化
      autoFocusFirstInput
      modalProps={{
        destroyOnClose: true,
        maskClosable: false,
      }}
      submitter={{
        searchConfig: {
          submitText: intl.formatMessage({ id: "pages.button.submit" }),
          resetText: intl.formatMessage({ id: "pages.button.cancel" }),
        },
      }}
      layout="horizontal"
      {...formItemLayout}
    >
      {/* 单列布局 - 移除了所有 ProForm.Group */}
      {/* <ProForm.Group></ProForm.Group>  */}
      <ProFormText
        name="customerCode"
        colProps={{ md: 12, xl: 8 }}
        label={intl.formatMessage({
          id: "pages.addForm.customer.customerCode",
        })}
        placeholder={intl.formatMessage({
          id: 'pages.addForm.customer.customerCode.placeholder',
          defaultMessage: '例如: C001'
        })}
        disabled={editStatus}
        fieldProps={{
          addonAfter: (
            <Tooltip
              title={intl.formatMessage({
                id: 'pages.addForm.customer.customerCode.tooltip',
                defaultMessage: '必须以C开头，4-10位字母/数字/下划线/连字符'
              })}
            >
              <QuestionCircleOutlined />
            </Tooltip>
          )
        }}
        rules={[
          {
            required: true,
            message: intl.formatMessage({ id: 'pages.addForm.customer.customerCode.required' })
          },
          {
            min: 4,
            max: 10,
            message: intl.formatMessage({ id: 'pages.addForm.customer.customerCode.length' })
          },
          {
            pattern: /^C[A-Za-z0-9_-]{3,9}$/,
            message: intl.formatMessage({ id: 'pages.addForm.customer.customerCode.format' })
          }
        ]}
      />

      <ProFormRadio.Group
        name="customerType"
        colProps={{ md: 12, xl: 8 }}
        label={intl.formatMessage({
          id: "pages.addForm.customer.customerType",
        })}
        initialValue="0"
        options={[
          {
            label: intl.formatMessage({
              id: "pages.addForm.customer.customerType.normal",
            }),
            value: "0", // 固定值
          },
          {
            label: intl.formatMessage({
              id: "pages.addForm.customer.customerType.agent",
            }),
            value: "1",
          },
        ]}
        rules={[{ required: true, message: "" }]}
      />

      <ProFormText
        name="customerName"
        label={intl.formatMessage({
          id: "pages.addForm.customer.customerName",
        })}
        placeholder={intl.formatMessage({ id: 'pages.addForm.customer.customerName' })}
        rules={[{ required: true, message: intl.formatMessage({ id: 'pages.addForm.customer.customerName' }),}]}
      />
      <ProFormText
        name="customerShortName"
        label={intl.formatMessage({
          id: "pages.addForm.customer.customerShortName",
        })}
        placeholder={intl.formatMessage({ id: 'pages.addForm.customer.customerShortName' })}
        rules={[{ required: true,message: intl.formatMessage({ id: 'pages.addForm.customer.customerShortName' }),}]}
      />
      <ProFormText
        name="legalPerson"
        label={intl.formatMessage({
          id: "pages.addForm.customer.legalPerson",
        })}
        placeholder={intl.formatMessage({ id: 'pages.addForm.customer.legalPerson' })}
        rules={[{ required: true,message: intl.formatMessage({ id: 'pages.addForm.customer.legalPerson' }), }]}
      />
      <ProFormText
        name="customerAddress"
        label={intl.formatMessage({
          id: "pages.addForm.customer.customerAddress",
        })}
        placeholder={intl.formatMessage({ id: 'pages.addForm.customer.customerAddress' })}
        rules={[{ required: true, message: intl.formatMessage({ id: 'pages.addForm.customer.customerAddress' }),}]}
      />
      <ProFormText
        name="customerPhone"
        label={intl.formatMessage({
          id: "pages.addForm.customer.customerPhone",
        })}
        placeholder={intl.formatMessage({ id: 'pages.addForm.customer.customerPhone' })}
        rules={[{ required: true, message: intl.formatMessage({ id: 'pages.addForm.customer.customerPhone' }),}]}
      />
      <ProFormText
        name="customerTelephone"
        label={intl.formatMessage({
          id: "pages.addForm.customer.customerTelephone",
        })}
        placeholder={intl.formatMessage({ id: 'pages.addForm.customer.customerTelephone' })}
      />
      <ProFormText
        name="customerDomain"
        label={intl.formatMessage({
          id: "pages.addForm.customer.customerDomain",
        })}
        placeholder={intl.formatMessage({ id: 'pages.addForm.customer.customerDomain' })}
      // rules={[{ required: true, message: "请输入公司网址" }]}
      />
      <ProFormText
        name="customerEmail"
        label={intl.formatMessage({
          id: "pages.addForm.customer.customerEmail",
        })}
        placeholder={intl.formatMessage({ id: 'pages.addForm.customer.customerEmail' })}
      />
      <ProFormUploadButton
        action="/admin-api/infra/file/upload"
        name="customerLogo"
        label={intl.formatMessage({
          id: "pages.addForm.customer.customerLogo",
        })}
        max={1} // 最多上传 1 张图片（设为 null 或更大的数字可支持多张）
        fieldProps={{
          accept: 'image/*', // 只允许上传图片
          listType: 'picture-card', // 缩略图样式
          customRequest: customUpload,
          fileList,
          onChange: ({ fileList: newList }) => {
            const patchedList = newList.map(file => {
              // response 可能是字符串或对象，根据你的接口定
              if (!file.url && typeof file.response === 'string') {
                file.url = file.response;
              } else if (!file.url && file.response?.url) {
                file.url = file.response.url;
              }
              return file;
            });

            setFileList(patchedList);
            form.setFieldsValue({ customerLogo: patchedList });
          },
          showUploadList: {
            showPreviewIcon: true,
            showDownloadIcon: true,
          },
          onPreview: file => {
            if (file.url) {
              window.open(file.url, '_blank');
            }
          },
        }}
      />

      <ProFormRadio.Group
        name="customerCurrency"
        label={intl.formatMessage({
          id: "pages.addForm.customer.customerCurrency",
        })}
        initialValue="USD"
        options={["USD", "CNY"]}
      />
      <ProFormRadio.Group
        name="customerCashType"
        label={intl.formatMessage({
          id: "pages.addForm.customer.customerCashType",
        })}
        initialValue="1"
        options={[
          {
            label: intl.formatMessage({
              id: "pages.addForm.customer.customerCashType.prepay",
            }),
            value: "1", // 建议使用固定值而不是显示文本
          },
          {
            label: intl.formatMessage({
              id: "pages.addForm.customer.customerCashType.bil",
            }),
            value: "2",
          },
        ]}
      />
      <ProFormDateRangePicker
        name="validPeriodDate"
        label={intl.formatMessage({
          id: "pages.addForm.customer.validPeriodDate",
        })}
      />
    </ModalForm>
  );
};

export default AddForm;
